/*
 * Copyright (C) 2012 yueyueniao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hqw.mindanews.fragment;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobUser;

import com.hqw.mindanews.MainActivity;
import com.hqw.mindanews.R;
import com.hqw.mindanews.SettingActivity;
import com.hqw.mindanews.adapter.MyFragmentPagerAdapter;
import com.hqw.mindanews.bean.User;
import com.hqw.mindanews.utils.DisplayUtil;
import com.hqw.mindanews.utils.Toastor;

public class ViewPageFragment extends Fragment implements OnClickListener {

	/*
	 * private Button showLeft; private Button showRight;
	 */

	private FrameLayout mLeftHeadContainer; // 左头像按钮
	private FrameLayout mRightHeadContainer; // 右边选项按钮
	private ImageView mUserHead;
	private MyAdapter mAdapter;
	private ViewPager mPager;
	TextView mNavView;
	/** 横条导航 */
	private HorizontalScrollView mHorizontalScrollView;
	private LinearLayout mLinearLayout;
	private ImageView mImageView;

	private int mScreenWidth; // 屏幕宽
	private int item_width;// item的宽

	private int endPosition; // 结束位置
	private int beginPosition; // 开始位置
	public boolean isEnd; // 是否在最后
	private int currentFragmentIndex; // 当前fragment的索引
	Toastor toastor;
	private User currentUser;
	private ArrayList<Fragment> pagerItemList = new ArrayList<Fragment>();

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// 获取屏幕宽
		toastor = new Toastor(getActivity());
		mScreenWidth = DisplayUtil.getDisplayWifth(getActivity());
		View view = initView(inflater);
	
		currentUser = BmobUser.getCurrentUser(getActivity(), User.class);
		
		initViewPager();
		initNav(); 

		return view;
	}

	private void initNav() {
		if (currentUser != null ) {
			if (currentUser.getBmobFile()!=null) {
				//加载头像
				currentUser.getBmobFile().loadImage(getActivity(), mUserHead);

			}
			
		}
		List<String> nav = new ArrayList<String>();
		nav.add("推荐");
		nav.add("校园");
		nav.add("社团");
		nav.add("活动");
		nav.add("通知");
		nav.add("兼职");
		nav.add("二手");

		for (int i = 0; i < nav.size(); i++) {
			RelativeLayout layout = new RelativeLayout(getActivity());
			mNavView = new TextView(getActivity());
			mNavView.setText(nav.get(i));
			RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			params.addRule(RelativeLayout.CENTER_IN_PARENT);
			layout.setId(100);
			layout.addView(mNavView, params);
			mLinearLayout.addView(layout, (int) (mScreenWidth / 4 + 0.5f), 50);
			layout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					mPager.setCurrentItem((Integer) v.getTag());

				}
			});

			layout.setTag(i);
		}

	}

	@SuppressWarnings("deprecation")
	private void initViewPager() {
		
		
//		NewFragment page1 = new NewFragment();
//		PageFragment2 page2 = new PageFragment2();
//		pagerItemList.add(page1);
//		pagerItemList.add(page2);
		for (int i = 0; i < 7; i++) { 
			Bundle data = new Bundle();
			data.putString("text", i + "");
			NewFragment fragment = new NewFragment();
			fragment.setArguments(data);
			pagerItemList.add(fragment);
		}
		mAdapter = new MyAdapter(getFragmentManager());
		
		MyFragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(
				getFragmentManager(), pagerItemList);
		
		
		mPager.setAdapter(fragmentPagerAdapter);
		mPager.setOnPageChangeListener(new MyPageChangeListener());
		mPager.setCurrentItem(0);

	}

	private View initView(LayoutInflater inflater) {
		View mView = inflater.inflate(R.layout.view_pager, null);
		// 导航条
		mHorizontalScrollView = (HorizontalScrollView) mView
				.findViewById(R.id.hsv_view);
		mLinearLayout = (LinearLayout) mView.findViewById(R.id.hsv_content);

		mImageView = (ImageView) mView.findViewById(R.id.img1);
		item_width = (int) ((mScreenWidth / 4.0 + 0.5f));
		mImageView.getLayoutParams().width = item_width;

		// 侧滑按钮
		mLeftHeadContainer = (FrameLayout) mView
				.findViewById(R.id.top_head_container);
		mRightHeadContainer = (FrameLayout) mView
				.findViewById(R.id.right_head_container);
		
		mPager = (ViewPager) mView.findViewById(R.id.pager);
		
		mUserHead = (ImageView) mView.findViewById(R.id.top_head);
		
		
		return mView;
	}

	public void onActivityCreated(Bundle savedInstanceState) {

		super.onActivityCreated(savedInstanceState);

		mLeftHeadContainer.setOnClickListener(this);

		mRightHeadContainer.setOnClickListener(this);

	}

	public boolean isFirst() {
		if (mPager.getCurrentItem() == 0)
			return true;
		else
			return false;
	}

	public boolean isEnd() {
		if (mPager.getCurrentItem() == pagerItemList.size() - 1)
			return true;
		else
			return false;
	}

	public class MyAdapter extends FragmentPagerAdapter {
		public MyAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public int getCount() {
			return pagerItemList.size();
		}

		@Override
		public Fragment getItem(int position) {

			Fragment fragment = null;
			if (position < pagerItemList.size())
				fragment = pagerItemList.get(position);
			else
				fragment = pagerItemList.get(0);

			return fragment;

		}
	}

	class MyPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int state) {
			if (state == ViewPager.SCROLL_STATE_DRAGGING) {
				isEnd = false;
			} else if (state == ViewPager.SCROLL_STATE_SETTLING) {
				isEnd = true;
				
				beginPosition = currentFragmentIndex * item_width;
				if (mPager.getCurrentItem() == currentFragmentIndex) {
					// 动画清除
					mImageView.clearAnimation();
					Animation animation = null;
					// 动画创建
					animation = new TranslateAnimation(endPosition,
							currentFragmentIndex * item_width, 0, 0);
					animation.setFillAfter(true);
					animation.setDuration(1);
					mImageView.startAnimation(animation);
					mHorizontalScrollView.invalidate();
					endPosition = currentFragmentIndex * item_width;
				}
			}
		}

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {
			if (!isEnd) {
				if (currentFragmentIndex == position) {
					endPosition = item_width * currentFragmentIndex
							+ (int) (item_width * positionOffset);
				}
				if (currentFragmentIndex == position + 1) {
					endPosition = item_width * currentFragmentIndex
							- (int) (item_width * (1 - positionOffset));
				}

				Animation mAnimation = new TranslateAnimation(beginPosition,
						endPosition, 0, 0);
				mAnimation.setFillAfter(true);
				mAnimation.setDuration(0);
				mImageView.startAnimation(mAnimation);
				mHorizontalScrollView.invalidate();
 				beginPosition = endPosition;
			}

		}

		@Override
		public void onPageSelected(int position) {
			Animation animation = new TranslateAnimation(endPosition, position
					* item_width, 0, 0);
			beginPosition = position * item_width;
			currentFragmentIndex = position;
			if (animation != null) {
				animation.setFillAfter(true);
				animation.setDuration(0);
				mImageView.startAnimation(animation);
				mHorizontalScrollView.smoothScrollTo((currentFragmentIndex - 1)
						* item_width, 0);
			}
		}

	}

	public interface MyPageChangeListenerIn {
		public void onPageSelected(int position);
	}

	@Override
	public void onResume() {
		Log.i("bmob", "重新渲染"); 
		if (currentUser != null ) {
			if (currentUser.getBmobFile()!=null) {
				//加载头像
				Log.i("bmob", "重新渲染头像"); 
			    currentUser = BmobUser.getCurrentUser(getActivity(), User.class);
				currentUser.getBmobFile().loadImage(getActivity(), mUserHead);

			}
			
		}
		super.onResume();
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.top_head_container:
			
			((MainActivity) getActivity()).showLeft();
			break;
		case R.id.right_head_container:
			((MainActivity) getActivity()).showRight();
			break;

		default:
			break;
		}

	}

}
